package com.purang.mathtest;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.LinearInterpolator;

import java.util.ArrayList;
import java.util.List;

public class CooGridView extends View {

    //成员变量
    private Paint mGridPaint;//网格画笔
    private Point mWinSize;//屏幕尺寸

    private int step = 100; //矩形的高度

    private int lableCountY = 6; // Y轴刻度个数
    private int intervalY = step; // y轴刻度的间隔
    private int intervalX = 130; // 坐标刻度的间隔
    private float minValueY; // y轴最小值
    private float maxValueY = 0; // y轴最大值
    private int firstPointX; //第一个点x坐标
    private int mHeight; // 控件高度
    private int mWidth; // 控件宽度
    private int paddingTop = 140;// 默认上下左右的padding
    private int paddingLeft = 0;
    private int paddingRight = 0;
    private int paddingDown = 50;
    private int leftRightExtra = intervalX / 3; //x轴左右向外延伸的长度
    private Paint paintWhite, paintBlue, paintRed, paintBack, paintText;
    private int originX; // 原点x坐标
    private int originY; // 原点y坐标
    private int firstMinX; // 移动时第一个点的最小x值
    private int firstMaxX; //移动时第一个点的最大x值
    private int xyTextSize = 24; //xy轴文字大小

    private int textToXYAxisGap = 0; // xy轴的文字距xy线的距离

    private int mLength = 7;//最大比例
    private int[] xPoints;//x轴的刻度集合
    private int[] yPoints;//y轴的刻度集合
    //    private float max = 7; //纵坐标最高点 ,寻找纵坐标最大值
    private float[] mPoints;//点的数组，-1表示该日还没到
    private float mFontSize = 12;//字体的大小
    private float mPointRadius = 1;//点的半径
    private Paint mShapePaint = new Paint();//阴影部分画笔
    private float mAnimatedValue = 1.0f;
    private String[] mXItems;//X轴的文字

    private int backGroundColor = Color.parseColor("#FFFFFF"); // view的背景颜色

    public CooGridView(Context context) {
        super(context);
    }

    public CooGridView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mGridPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        //准备屏幕尺寸
        mWinSize = new Point();

        paintBlue = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintBlue.setColor(Color.GRAY);
        paintBlue.setStrokeWidth(8f);
        paintBlue.setStyle(Paint.Style.STROKE);

        paintBack = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintBack.setColor(Color.parseColor("#272727"));
        paintBack.setStyle(Paint.Style.FILL);

        paintWhite = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintWhite.setColor(Color.WHITE);
        paintWhite.setStyle(Paint.Style.STROKE);

        paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintText.setColor(Color.GRAY);
        paintText.setTextSize(xyTextSize);
        paintText.setStrokeWidth(2f);

        //阴影部分画笔
        mShapePaint.setAntiAlias(true);
        mShapePaint.setStyle(Paint.Style.FILL);
        mShapePaint.setColor(Color.parseColor("#DAE5FB"));

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mWinSize.x = getWidth();
                mWinSize.y = getHeight() - paddingDown - 10;
            }
        });
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if (changed) {
            mWidth = getWidth();
            mHeight = getHeight();

            originX = paddingLeft - leftRightExtra;
            originY = mHeight - paddingDown;

            firstPointX = paddingLeft;
            firstMinX = mWidth - originX - (mXItems.length - 1) * intervalX - leftRightExtra;
            // 滑动时，第一个点x值最大为paddingLeft，在大于这个值就不能滑动了
            firstMaxX = firstPointX;
            setBackgroundColor(backGroundColor);
        }
        super.onLayout(changed, left, top, right, bottom);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        HelpDraw.drawGrid(canvas, mWinSize, mGridPaint);
        drawGrid(canvas);
        drawBrokenLine(canvas);
        drawX(canvas);
    }

    private void drawGrid(Canvas canvas) {
        Path path = new Path();
        // 画水平线
        for (int i = 0; i < mHeight / step + 1; i++) {
            path.moveTo(0, step * i);// (0,0) (0,100) (0,200)
            path.lineTo(mWidth, step * i); //(width,0) (width,100) (width,200)
        }
        // 画垂直线
        for (int i = 0; i < mWidth / step; i++) {
            path.moveTo(step * i * 2, 0);// (200,0)(400,0)
            path.lineTo(step * i * 2, mHeight - step);// (0,)
        }
        mGridPaint.setStrokeWidth(1);
        mGridPaint.setColor(Color.GRAY);
        mGridPaint.setStyle(Paint.Style.STROKE);
        canvas.drawPath(path, mGridPaint);
    }

    protected void OnAnimationUpdate(ValueAnimator valueAnimator) {
        mAnimatedValue = (float) valueAnimator.getAnimatedValue();
        invalidate();
    }

    public ValueAnimator valueAnimator;

    private ValueAnimator startViewAnim(float startF, final float endF, long time) {
        valueAnimator = ValueAnimator.ofFloat(startF, endF);
        valueAnimator.setDuration(time);
        valueAnimator.setInterpolator(new LinearInterpolator());

//        valueAnimator.setRepeatCount(ValueAnimator.INFINITE);

//        valueAnimator.setRepeatMode(ValueAnimator.RESTART);

        valueAnimator.setRepeatMode(ValueAnimator.REVERSE);

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                OnAnimationUpdate(valueAnimator);

            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);

            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                super.onAnimationRepeat(animation);
            }
        });
        if (!valueAnimator.isRunning()) {
            valueAnimator.start();
        }

        return valueAnimator;
    }

    private void drawX(Canvas canvas) {

        int yOrigin = mHeight - step;

        Path shapePath = new Path();

        for (int i = 0; i < mLength; i++) {

            //获取点的坐标
            if (i == 0) {
                xPoints[i] = (int) ((i) * (mWidth / mLength));// 54 162 270 378 476
            } else {
                xPoints[i] = (int) ((i + 0.5) * (mWidth / mLength));// 54 162 270 378 476
            }

            yPoints[i] = (int) ((maxValueY - (mPoints[i] == -1 ? 0 :
                    mPoints[i]) * mAnimatedValue) * ((mHeight - mLength * mFontSize) / maxValueY) + 4 * mFontSize); // 528 528 528 528 528
            if (i > 0) {
                //画一个实心梯形,阴影部分
                shapePath.moveTo(xPoints[i - 1], yOrigin + mPointRadius / 2);// (54,528)(162)
                shapePath.lineTo(xPoints[i - 1], yPoints[i - 1]);
                shapePath.lineTo(xPoints[i], yPoints[i]);
                shapePath.lineTo(xPoints[i], yOrigin + mPointRadius / 2);
            }
            shapePath.close();
            canvas.drawPath(shapePath, mShapePaint);
            // x轴上的文字  firstPointX + i * intervalX,
            if (i == 0) {
                canvas.drawText(mXItems[i], 0, originY + textToXYAxisGap + getTextHeight(paintText, "17.01"), paintText);
            } else {
                canvas.drawText(mXItems[i], xPoints[i] - getTextWidth(paintText, mXItems[i]) / 2,
                        originY + textToXYAxisGap + getTextHeight(paintText, "17.01"), paintText);
            }
        }
    }

    private void drawBrokenLine(Canvas canvas) {
        canvas.save();

        // 画折线
        float aver = (lableCountY - 1) * intervalY / (maxValueY - minValueY); //平均值
        Path path = new Path();
        for (int i = 0; i < mPoints.length; i++) {
            int y = (int) ((maxValueY - (mPoints[i] == -1 ? 0 :
                    mPoints[i]) * mAnimatedValue) * ((mHeight - mLength * mFontSize) / maxValueY) + 4 * mFontSize);
            int x = (int) ((i + 0.5) * (mWidth / mLength));
//            float yyyy = mHeight - paddingDown - leftRightExtra - mPoints[i] * aver + minValueY * aver;
            if (i == 0) {
                path.moveTo(firstPointX, y);//(0,283)
            } else {
                path.lineTo(firstPointX + x, y);//(130,391.8)
            }
        }
        canvas.drawPath(path, paintBlue);
        //将折线超出x轴坐标的部分截取掉（左边）
        paintBack.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
        RectF rectF = new RectF(0, 0, originX, mHeight);
        canvas.drawRect(rectF, paintBack);
        canvas.restore();
    }


    public void setData(ArrayList<LineChartData> data) {
        mLength = data.size();
        if (mLength > 0) {
            mXItems = new String[mLength];
            mPoints = new float[mLength];
            for (int i = 0; i < mLength; i++) {
                mPoints[i] = data.get(i).getPoint();
                mXItems[i] = data.get(i).getItem();
            }
        }

        minValueY = mPoints[0];
        for (int i = 0; i < mPoints.length; i++) {
            // 找出y轴的最大最小值
            if (mPoints[i] > maxValueY) {
                maxValueY = mPoints[i];
            }
            if (mPoints[i] < minValueY) {
                minValueY = mPoints[i];
            }

        }

        xPoints = new int[mLength];//x轴的刻度集合
        yPoints = new int[mLength];//y轴的刻度集合
//        startViewAnim(0f, 1f, 1000);
//        this.xValues = xValues;
    }

    public void setYValues(List<Integer> yValues) {
//        this.yValues = yValues;
    }

    /**
     * 获取文字的宽度
     *
     * @param paint
     * @param text
     * @return
     */
    private int getTextWidth(Paint paint, String text) {
        return (int) paint.measureText(text);
    }

    /**
     * 获取文字的高度
     *
     * @param paint
     * @param text
     * @return
     */
    private int getTextHeight(Paint paint, String text) {
        Rect rect = new Rect();
        paint.getTextBounds(text, 0, text.length(), rect);
        return rect.height();
    }

}
